//
//  UserAccount.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/13.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit
import Alamofire

class UserAccount: NSObject , Printable, NSCoding{
    
//    access_token	用于调用access_token，接口获取授权后的access token
    var access_token: String
//    expires_in	access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval
//    uid	当前授权用户的UID
    var uid: String?
    
    
//    用户名
    var name: String?
//    头像
    var avatar_large: String?
    init(dict:[String: AnyObject]) {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        uid = dict["uid"] as? String
    }
    
    
    /// 归档路径
    static let archivePath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String).stringByAppendingPathComponent("account.plist")
    
    
    // 解档
    required init(coder aDecoder: NSCoder) {
        expires_in = aDecoder.decodeDoubleForKey("expires_in") as NSTimeInterval
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
    }

    
    // 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(uid, forKey: "uid")
    }
    
    
    // 获取访问令牌
    class func loadAccessToken(params: [String: AnyObject],completionHandler:(user: UserAccount?) -> ()) {//completionHandler
        let urlstring = "https://api.weibo.com/oauth2/access_token"
        
        NetWorkingTools.requestJSON(.POST, URLString: urlstring, parameters: params) { (JSON) -> () in

            // 获取访问令牌
            let account = UserAccount(dict: (JSON as? [String: AnyObject])!)
            
            // 通过令牌加载完整的,用户信息
            account.loadUserinfo({ (user) -> () in
                // 归档,保证获取到了信息后在归档
                NSKeyedArchiver.archiveRootObject(user!, toFile: self.archivePath)
                
                // 回调,设置为后面切换页面做铺垫 全局变量为登陆状态
                completionHandler(user: account)
            })
        }
        
       
    }

    
    
    // 加载用户信息
    func loadUserinfo(completionHandler:(user: UserAccount?) -> ()) {
        // https://api.weibo.com/2/users/show.json?access_token=2.00rWncND09E5eM3e01a4f175FYRh8C&uid=2949737721
        // 用户信息http://weibo.com/2949737721/profile?topnav=1&wvr=6
        let urlstring = "https://api.weibo.com/2/users/show.json"
        
        
        // 注意参数 uid 后面接  !
        let params = ["access_token": access_token, "uid": uid!]
        NetWorkingTools.requestJSON(.GET, URLString: urlstring, parameters: params) { (JSON) -> () in
            let dict = JSON as! [String: AnyObject]
            self.avatar_large = dict["avatar_large"] as? String
            self.name = dict["name"] as? String
            completionHandler(user: self)
        }
        
    }
    
    
    
    // 解档获取登陆信息
    class func loadUserAccount() -> UserAccount? {
        // 解档获取对象
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as? UserAccount {
            // 判断是否过期.过期就返回nil
            let date =  NSDate(timeIntervalSinceNow: account.expires_in)
            
            // 升序,就是比较小
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        
        }
        return nil
    }
    
    
    // 清除用户信息,注销
    class func logoutUserAccount() -> Bool {
        println("用户注销")
        let fileManager = NSFileManager.defaultManager()
        
        // 文件存在就删除
        if fileManager .fileExistsAtPath(archivePath) {
            var err: NSError?
            fileManager.removeItemAtPath(archivePath, error: &err)
            return err == nil
        }
        return true
    }
    
    
    override var description:String {
        let property = ["avatar_large", "access_token", "expires_in", "name", "uid"]
        return "\(dictionaryWithValuesForKeys(property))"
    }
    
}












